<template>
  <div class="water-quality-calendar">
    <!-- 日历头部：年月选择器和操作按钮 -->
    <div class="calendar-header">
      <el-button
        icon="el-icon-arrow-left"
        size="mini"
        @click="prevMonth"
        class="header-btn"
      ></el-button>
      <el-date-picker
        v-model="currentDate"
        type="month"
        format="yyyy年MM月"
        value-format="yyyy-MM"
        @change="handleDateChange"
        placeholder="选择月份"
        class="month-picker"
      ></el-date-picker>
      <el-button
        icon="el-icon-arrow-right"
        size="mini"
        @click="nextMonth"
        class="header-btn"
      ></el-button>
      <el-button type="primary" size="mini" @click="today" class="today-btn">
        今天
      </el-button>
    </div>

    <!-- 星期标题 -->
    <div class="week-days">
      <div class="week-day" v-for="(day, index) in weekDays" :key="index">
        {{ day }}
      </div>
    </div>

    <!-- 日历主体：日期网格 -->
    <div class="calendar-grid">
      <div
        class="calendar-day"
        v-for="(day, index) in calendarDays"
        :key="index"
        :class="{
          'prev-month': day.month !== currentMonth,
          'current-month': day.month === currentMonth,
          today: day.isToday,
          'quality-excellent': day.quality === 'excellent',
          'quality-good': day.quality === 'good',
          'quality-poor': day.quality === 'poor',
          'quality-bad': day.quality === 'bad',
        }"
        @click="handleDayClick(day)"
      >
        <div class="day-number">{{ day.date }}</div>
        <div class="quality-indicator" v-if="day.month === currentMonth"></div>
      </div>
    </div>

    <!-- 图例说明 -->
    <div class="quality-legend">
      <div class="legend-item" v-for="(item, key) in qualityLevels" :key="key">
        <div class="legend-color" :class="'quality-' + key"></div>
        <div class="legend-text">{{ item }}</div>
      </div>
    </div>

    <!-- 详情弹窗 -->
    <el-dialog
      title="水质详情"
      :visible.sync="detailVisible"
      width="30%"
      @close="handleClose"
    >
      <div v-if="selectedDay">
        <p>
          <strong>日期：</strong>{{ selectedDay.year }}年{{
            selectedDay.month
          }}月{{ selectedDay.date }}日
        </p>
        <p>
          <strong>水质等级：</strong
          >{{ qualityLevels[selectedDay.quality] || "无数据" }}
        </p>
        <p>
          <strong>pH值：</strong
          >{{ (selectedDay.details && selectedDay.details.ph) || "未知" }}
        </p>
        <p>
          <strong>溶解氧：</strong
          >{{ (selectedDay.details && selectedDay.details.do) || "未知" }} mg/L
        </p>
        <p>
          <strong>浊度：</strong
          >{{
            (selectedDay.details && selectedDay.details.turbidity) || "未知"
          }}
          NTU
        </p>
        <p>
          <strong>评价：</strong
          >{{
            (selectedDay.details && selectedDay.details.comment) || "无评价"
          }}
        </p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "WaterQualityCalendar",
  data() {
    return {
      // 当前选择的日期（月份）
      currentDate: "",
      // 日历显示的日期数据
      calendarDays: [],
      // 星期标题
      weekDays: ["日", "一", "二", "三", "四", "五", "六"],
      // 水质等级
      qualityLevels: {
        excellent: "优",
        good: "良好",
        poor: "轻度污染",
        bad: "重度污染",
      },
      // 详情弹窗显示状态
      detailVisible: false,
      // 当前选中的日期
      selectedDay: null,
      // 当前月份（数字）
      currentMonth: 0,
    };
  },
  mounted() {
    // 初始化显示当前月份
    const today = new Date();
    this.currentDate = this.formatDate(today, "yyyy-MM");
    this.generateCalendar();
  },
  methods: {
    // 生成日历数据
    generateCalendar() {
      if (!this.currentDate) return;

      const [year, month] = this.currentDate.split("-").map(Number);
      this.currentMonth = month;

      // 获取当月第一天
      const firstDay = new Date(year, month - 1, 1);
      // 获取当月最后一天
      const lastDay = new Date(year, month, 0);

      // 当月第一天是星期几（0-6）
      const firstDayOfWeek = firstDay.getDay();
      // 当月的总天数
      const totalDays = lastDay.getDate();

      // 日历需要显示的总天数（6行×7列=42天）
      const calendarDays = [];

      // 添加上月的补充天数
      const prevMonth = month - 1 || 12;
      const prevMonthYear = prevMonth === 12 ? year - 1 : year;
      const prevMonthLastDay = new Date(prevMonthYear, prevMonth, 0).getDate();

      for (let i = 0; i < firstDayOfWeek; i++) {
        const date = prevMonthLastDay - firstDayOfWeek + i + 1;
        calendarDays.push(
          this.createDayObject(prevMonthYear, prevMonth, date, false)
        );
      }

      // 添加当月的天数
      for (let i = 1; i <= totalDays; i++) {
        const isToday = this.isSameDay(
          new Date(year, month - 1, i),
          new Date()
        );
        calendarDays.push(this.createDayObject(year, month, i, isToday));
      }

      // 添加下月的补充天数
      const nextMonth = month + 1 > 12 ? 1 : month + 1;
      const nextMonthYear = nextMonth === 1 ? year + 1 : year;
      const remainingDays = 42 - calendarDays.length;

      for (let i = 1; i <= remainingDays; i++) {
        calendarDays.push(
          this.createDayObject(nextMonthYear, nextMonth, i, false)
        );
      }

      this.calendarDays = calendarDays;
    },

    // 创建日期对象
    createDayObject(year, month, date, isToday) {
      // 随机生成水质数据（实际应用中应从API获取）
      const qualityTypes = ["excellent", "good", "poor", "bad", null];
      const randomQuality =
        qualityTypes[Math.floor(Math.random() * qualityTypes.length)];

      return {
        year: year,
        month: month,
        date: date,
        isToday: isToday,
        quality: randomQuality,
        // 详细数据
        details: randomQuality
          ? this.generateQualityDetails(randomQuality)
          : null,
      };
    },

    // 生成水质详细数据
    generateQualityDetails(quality) {
      // 根据水质等级生成不同范围的模拟数据
      switch (quality) {
        case "excellent":
          return {
            ph: (7.0 + Math.random() * 0.5).toFixed(1),
            do: (8.0 + Math.random() * 1.0).toFixed(1),
            turbidity: (1.0 + Math.random() * 0.5).toFixed(1),
            comment: "水质优良，适合各类用水需求",
          };
        case "good":
          return {
            ph: (6.5 + Math.random() * 1.0).toFixed(1),
            do: (6.5 + Math.random() * 1.5).toFixed(1),
            turbidity: (1.5 + Math.random() * 1.0).toFixed(1),
            comment: "水质良好，可满足一般用水需求",
          };
        case "poor":
          return {
            ph: (6.0 + Math.random() * 1.0).toFixed(1),
            do: (4.0 + Math.random() * 2.5).toFixed(1),
            turbidity: (2.5 + Math.random() * 2.5).toFixed(1),
            comment: "轻度污染，不适合直接饮用",
          };
        case "bad":
          return {
            ph: (5.5 + Math.random() * 1.0).toFixed(1),
            do: (2.0 + Math.random() * 2.0).toFixed(1),
            turbidity: (5.0 + Math.random() * 5.0).toFixed(1),
            comment: "重度污染，禁止任何与人体直接接触的用途",
          };
        default:
          return null;
      }
    },

    // 格式化日期
    formatDate(date, format) {
      const year = date.getFullYear();
      const month = date.getMonth() + 1;

      return format
        .replace("yyyy", year)
        .replace("MM", month.toString().padStart(2, "0"));
    },

    // 判断两个日期是否是同一天
    isSameDay(date1, date2) {
      return (
        date1.getFullYear() === date2.getFullYear() &&
        date1.getMonth() === date2.getMonth() &&
        date1.getDate() === date2.getDate()
      );
    },

    // 切换到上一个月
    prevMonth() {
      if (!this.currentDate) return;

      const [year, month] = this.currentDate.split("-").map(Number);
      let newYear = year;
      let newMonth = month - 1;

      if (newMonth < 1) {
        newMonth = 12;
        newYear--;
      }

      this.currentDate = `${newYear}-${newMonth.toString().padStart(2, "0")}`;
    },

    // 切换到下一个月
    nextMonth() {
      if (!this.currentDate) return;

      const [year, month] = this.currentDate.split("-").map(Number);
      let newYear = year;
      let newMonth = month + 1;

      if (newMonth > 12) {
        newMonth = 1;
        newYear++;
      }

      this.currentDate = `${newYear}-${newMonth.toString().padStart(2, "0")}`;
    },

    // 回到今天
    today() {
      const today = new Date();
      this.currentDate = this.formatDate(today, "yyyy-MM");
    },

    // 日期选择器变化时
    handleDateChange(value) {
      if (value) {
        this.currentDate = value;
      }
    },

    // 点击日期
    handleDayClick(day) {
      this.selectedDay = day;
      this.detailVisible = true;
    },

    // 关闭详情弹窗
    handleClose() {
      this.detailVisible = false;
      this.selectedDay = null;
    },
  },
  watch: {
    currentDate: {
      handler() {
        this.generateCalendar();
      },
      immediate: false,
    },
  },
};
</script>

<style scoped>
.water-quality-calendar {
  font-family: "Microsoft YaHei", sans-serif;
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.calendar-header {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
}

.header-btn {
  margin: 0 10px;
}

.month-picker {
  width: 180px;
  text-align: center;
}

.today-btn {
  margin-left: 15px;
}

.week-days {
  display: flex;
  margin-bottom: 10px;
}

.week-day {
  flex: 1;
  text-align: center;
  padding: 10px 0;
  font-weight: bold;
  color: #666;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 5px;
}

.calendar-day {
  aspect-ratio: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  position: relative;
  cursor: pointer;
  transition: all 0.2s;
}

.calendar-day:hover {
  background-color: #f5f7fa;
}

.day-number {
  font-size: 14px;
}

.prev-month .day-number {
  color: #ccc;
}

.current-month .day-number {
  color: #333;
}

.today {
  border: 1px solid #409eff;
}

.quality-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-top: 5px;
}

/* 水质颜色 */
.quality-excellent .quality-indicator {
  background-color: #52c41a; /* 绿色 - 优 */
}

.quality-good .quality-indicator {
  background-color: #1890ff; /* 蓝色 - 良好 */
}

.quality-poor .quality-indicator {
  background-color: #faad14; /* 黄色 - 轻度污染 */
}

.quality-bad .quality-indicator {
  background-color: #f5222d; /* 红色 - 重度污染 */
}

/* 图例 */
.quality-legend {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  flex-wrap: wrap;
}

.legend-item {
  display: flex;
  align-items: center;
  margin: 0 10px;
  font-size: 14px;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 5px;
}
</style>
